#!/usr/bin/python
import socket,traceback
import os,time
import json,threading
from Dev_state import Dev

class Json_encoder(json.JSONEncoder):
    def default(self,obj):
        d = {}
        d['__class__'] = obj.__class__.__name__
        d['__module__'] = obj.__module__
        d.update(obj.__dict__)
        return d
class Json_decoder(json.JSONDecoder):
    def __init__(self):
        json.JSONDecoder.__init__(self,object_hook=self.dict2object)
    def dict2object(self,d):
        if '__class__' in d:
            class_name = d.pop('__class__')
            module_name = d.pop('__module__')
            module = __import__(module_name)
            class_ = getattr(module,class_name)
            args = dict((key.encode('ascii') ,value ) for key ,value in d.items())
            inst = class_(**args)
        else:
            inst = d
        return inst


class Child_sock:
    def __init__(self,host,port,data):
        
        self.stack = data
        try:
            self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            self.sock.bind((host,port))
            self.sock.listen(1)
        
        except socket.error ,e:
            print "Net connecting error : %s" %e
    def parse_json(self,json_obj):
        obj = Json_decoder().decode(json_obj)
        return obj
    def encode_json(self,d):
        json_obj =  Json_encoder().encode(d)
        return json_obj
    
    def run(self):

        while True:
            try:
                clientsocket ,clientaddr = self.sock.accept()
            except KeyboardInterrupt :
                raise
            except socket.error, e :
                print "client error : %s" %e
            if clientsocket.getpeername() :
                print "Connecting in :\n ", clientsocket.getpeername()
                request = clientsocket.recv(4096)
                print "new: " ,request
                if (request != "stop"):
                    #request = self.parse_json(request)
                    print "get ...\n",request,"\no"
                    
                elif request == "stop":
                    print "Stop In child"

                    try:
                        print "Connecting", clientsocket.getpeername(),
                        clientsocket.close()
                        print "ok"
                    except :
                        print "stop error"
                        traceback.print_exc()
                    return "no"
                else :
                    continue
                try:
                    request = self.parse_json(request)
                except ValueError:
                    print "parse error"
                print "old :",self.stack[request['name']]
                if (request['state'] != self.stack[request['name']]['state']):
                    self.stack[request['name']]['state'] = request['state']
                    response_temp = self.stack[request['name']]
                    response = self.encode_json(response_temp)
                    clientsocket.sendall(response)
                    print "changed : \n",self.stack[request['name']]
                else :
                    clientsocket.sendall("you are error!!\n")
                    continue
    def Upstack(self):
        return self.stack
                       
            
                
if __name__ == '__main__':
    a= {}
    b= Dev("a1","on").getDeviceInformation()
    c = Dev('a2','off').getDeviceInformation()
    d=  Dev("Ouyang",'off').getDeviceInformation()
    a['a1'] = b
    a['a2'] = c
    a['Ouyang'] = d
    ser = Child_sock('',50001,a)
    ser.listen()
        
